﻿using Easy.Cloud.Communication.Sms.Core;
using Easy.Cloud.Communication.Sms.Submail.Options;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Easy.Shared.Exception;
using static System.Net.Mime.MediaTypeNames;

namespace Easy.Cloud.Communication.Sms.Submail
{
    public class SubmailSmsClient : ISmsClient
    {
        private readonly HttpClient _httpClient;
        private readonly SubmailOptions _submailOptions;

        public SubmailSmsClient(IHttpClientFactory httpClientFactory, SubmailOptions submailOptions)
        {
            _httpClient = httpClientFactory.CreateClient(nameof(SubmailSmsClient));
            _submailOptions = submailOptions;
        }

        public async Task<ResponseMessage> SendAsync(SendRequest request)
        {
            var template = _submailOptions.TemplateItem.Single(s => s.Name.Equals(request.Template));

            var requestJson = JsonSerializer.Serialize(new Request(
                _submailOptions.AppID,
                request.PhoneNumbers,
                template.ToString(),
                _submailOptions.Appkey,
                request.TemplateParam));

            var httpContent = new StringContent(requestJson, Encoding.UTF8);

            try
            {
                var response = await _httpClient.PostAsync(Constants.SmsXsend, httpContent);

                response.EnsureSuccessStatusCode();

                using (var contentStream = await response.Content.ReadAsStreamAsync())
                {
                    var result = await JsonSerializer.DeserializeAsync<SubmailHttpResponseMessage>(contentStream);

                    if (result.status.Equals("success"))
                        return new ResponseMessage(true, request);

                    return new ResponseMessage(false, result);
                }
            }
            catch (Exception e)
            {
                throw new SubmailException(e.ConvertString());
            }
        }
    }
}